import json,requests,base64,getpass
from selenium import webdriver
from time import sleep
from datetime import datetime
from io import BytesIO
from PIL import Image
from sys import version_info
from selenium.webdriver.remote.webelement import WebElement

def init():
    chrome_options = webdriver.ChromeOptions()
    # chrome_options.add_argument("--proxy-server=http://218.75.158.153:3128")  # 代理ip
    #chrome_options.add_argument('--headless')   # 增加无界面选项
    chrome_options.add_argument('--disable-gpu')  # 如果不加这个选项，有时定位会出现问题
    chrome_options.add_argument('--window-size=1920,1080')   # 设置窗口大小, 窗口大小会有影响
    return webdriver.Chrome(options=chrome_options,executable_path="c://chromedriver.exe")  # 地址为chromedriver.exe的地址
    # 启动浏览器，获取网页源代码

def wangke(name,u,cookie):
    url = "https://mooc.yinghuaonline.com/user/login"
    if cookie!="" and cookie!=None:
        token = {'name': 'token', 'value': cookie}
        u.get(url)
        u.add_cookie(token)
        u.get('https://mooc.yinghuaonline.com/user/')
    else:
        u.get(url)
        sleep(1)
        u.find_element_by_id('schoolId').click()
        u.find_element_by_xpath('//select/option[@value="15"]').click()  # value=15选的是中南林业科技大学涉外学院
        u.find_element_by_id('username').send_keys(username)
        u.find_element_by_id('password').send_keys(password)
        u.find_element_by_id('remember').click()
        u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
        sleep(1)
        try:
            u.find_element_by_xpath('//div/a[@class="layui-layer-btn0"]').click()
            cookies = u.get_cookies()
            cookie = cookies[0]['name']+'='+cookies[0]['value']+';'+cookies[1]['name']+'='+cookies[1]['value']
            print('当前使用：'+cookie)
            download('https://mooc.yinghuaonline.com/service/code?r={time()}',cookie)
            img_path = "1.jpg"
            img = Image.open(img_path)
            result = base64_api(uname='yusheng615', pwd='1731249586', img=img)

            u.find_element_by_id('code').send_keys(result)
            u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
        except:
            print("出差了")
            u.quit()
        sleep(3)
        try:
            print(getwximage(u,username))
            input("微信扫码后回车")
        except:
            print("不需要扫码")
    sleep(3)
    cookies = u.get_cookies()
    cookie = "token="+cookies[2]['value']
    # 停2秒等加载
    sleep(2)
    # 选择课程
    course_list = u.find_elements_by_xpath('/html/body/div[3]/div[2]/div[2]/div[1]/div[4]/div/div/div[2]/div[1]/a')
    course_list[int(name)-1].click()
    print("登录成功")

    # 停5秒等加载
    sleep(2)
    # 查询学习状态
    url = u.find_element_by_link_text("学习成绩").get_attribute('href')
    u.get(url)
    sleep(0.2)
    total_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[2]')
    print("已经学习 %s 个视频" % total_catalog.text)
    num = int(total_catalog.text)
    surplus_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[3]')
    print("尚未学习 %s 个视频" % surplus_catalog.text)
    sleep(0.5)
    flag = 0
    n1 = 0
    n2 = 0
    while 1:
        try:
            #未学完
            u.find_element_by_id('state').click()
            u.find_element_by_xpath('//*[@id="state"]/option[3]').click()
            u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
            sleep(0.5)
            href_list1 = u.find_elements_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a')
            u.get(href_list1[n1].get_attribute('href'))
        except:
            flag = 1
        try:
            #未学
            if flag == 1:
                u.find_element_by_id('state').click()
                u.find_element_by_xpath('//*[@id="state"]/option[2]').click()
                u.find_element_by_xpath('//*[@id="searchForm"]/input[2]').click()
                sleep(0.5)
                href_list2 = u.find_elements_by_xpath('//*[@id="list"]/tbody/tr/td[1]/a')
                u.get(href_list2[n2].get_attribute('href'))
        except:
            break

        # 播放
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[1]/canvas').click()
        sleep(5)
        try:
            yzm = u.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]/div/div[2]/img[2]').get_attribute('src')
            #yzm = "http://www.minghuaetc.com/"+yzm

            download(yzm,cookie)
            img_path = "1.jpg"
            img = Image.open(img_path)
            result = base64_api(uname='gksec', pwd='water123', img=img)
            
            u.find_element_by_xpath('//*[@id="layui-layer1"]/div[2]/div/div[2]/input[2]').send_keys(result)
            u.find_element_by_link_text("开始播放").click()
        except:
            print("无验证码")
        # 静音
        u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[17]/canvas').click()
        
        print("开始时间是%s" % datetime.now())
        # 每个视频停留
        time = u.find_element_by_xpath('//*[@id="videoContent"]/div/div[2]/div[8]')
        time = str(time.text)
        if time[8:10] == '00' and time[11:13] == '00':
            if flag == 0:
                n1 += 1
            else:
                n2 += 1
        sleep(int(time[8:10]) * 60 + 60)
        print("结束时间是%s" % datetime.now())
        u.get(url) #返回学习记录处
        sleep(0.2)
        total_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[2]')
        print("已经学习 %s 个视频" % total_catalog.text)
        num = int(total_catalog.text)
        surplus_catalog = u.find_element_by_xpath('//*[@id="searchForm"]/span/span[3]')
        print("尚未学习 %s 个视频" % surplus_catalog.text)
        sleep(0.5)
            
    # 退出
    print("完成")
    u.quit()
    
def getwximage(u,username):
    url=u.find_element_by_class_name("qrcode").get_attribute('src')
    r = requests.get(url)
    with open(username+'.png', 'wb') as f:
            f.write(r.content)#保存
            return "微信二维码已保存在此目录"
    
def base64_api(uname, pwd,  img):
    img = img.convert('RGB')
    buffered = BytesIO()
    img.save(buffered, format="JPEG")
    if version_info.major >= 3:
        b64 = str(base64.b64encode(buffered.getvalue()), encoding='utf-8')
    else:
        b64 = str(base64.b64encode(buffered.getvalue()))
    data = {"username": uname, "password": pwd, "image": b64}
    result = json.loads(requests.post("http://api.ttshitu.com/base64", json=data).text)
    if result['success']:
        return result["data"]["result"]
    else:
        return result["message"]
    return ""

def download(url, cookie):
    header = {
        "Cookie": cookie,
        }
    r = requests.get(url, headers=header)
    with open('1.jpg', 'wb') as f:
        f.write(r.content)

def fakecookie(cookie,u):
    username = input("请输入账号：")
    password = getpass.getpass("请输入密码：")
    token = {'name': 'token', 'value': cookie}
    u.get('https://mooc.yinghuaonline.com/user/login')
    u.add_cookie(token)
    u.find_element_by_id('schoolId').click()
    u.find_element_by_xpath('//select/option[@value="15"]').click()  # value=15选的是中南林业科技大学涉外学院
    u.find_element_by_id('username').send_keys(username)
    u.find_element_by_id('password').send_keys(password)
    u.find_element_by_id('remember').click()
    u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
    sleep(1)
    try:
        u.find_element_by_xpath('//div/a[@class="layui-layer-btn0"]').click()
        cookies = u.get_cookies()
        cookie = cookies[0]['name']+'='+cookies[0]['value']+';'+cookies[1]['name']+'='+cookies[1]['value']
        print('当前使用：'+cookie)
        download('https://mooc.yinghuaonline.com/service/code?r={time()}',cookie)
        img_path = "1.jpg"
        img = Image.open(img_path)
        result = base64_api(uname='yusheng615', pwd='1731249586', img=img)

        u.find_element_by_id('code').send_keys(result)
        u.find_element_by_xpath('//div[@class="inpbox"]/input[@value="登录"]').click()
    except:
        print("出差了")
    
    u.quit()

if __name__ == "__main__":
    cookie=input("请输入可用token（选填）：")
    if cookie!="" and cookie!=None:
        if input("是否进行token重绑(y/n):") =="y":
            fakecookie(cookie,init())
        
    if cookie=="" or cookie==None:
        username = input("请输入账号：")
        password = getpass.getpass("请输入密码：")
    name_list = input("请输入网课编号：")

    for i in name_list:
        wangke(i,init(),cookie)
    
